package com.atguigu.test01;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class CookByThreadPoolExecutor02 {

    private static AtomicInteger cooks = new AtomicInteger(50);
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                4,
                4,
                30,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                //new ThreadPoolExecutor.AbortPolicy()
                //new ThreadPoolExecutor.DiscardPolicy()
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        try {
                            Thread.sleep(1);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        executor.submit(r);
                    }
                }
        );


        while (true){
            threadPoolExecutor.submit(() -> {
                if(cooks.get()<=0){
                    System.out.println("已售完");
                    return 0;
                }
                System.out.println(Thread.currentThread().getName()+" 售前：" +cooks.get());
                cooks.decrementAndGet();
                System.out.println(Thread.currentThread().getName()+" 售后：" +cooks.get());
                return 0;
            });
            if(cooks.get()<=0){
                System.out.println("已售完");
                return;
            }
        }
    }
}
